import * as ui from 'maishu-ui-toolkit';
import React = require('react');
import { ShoppingService } from 'mobile/services/shoppingService';
import { AccountService } from 'mobile/services/accountService';
import { PageProps, Application } from 'maishu-chitu-react';
import { defaultNavBar, formatDate } from 'mobile/site';
import { SpinerComponent, Status } from 'controls/spiner-component';
import { WeiXinService } from 'mobile/services/weixinService';

interface Props extends PageProps {
    // order: Order
    data: {
        id: string
    }
}

interface State {
    payType: PayType,
    status?: Status,
    order?: Order,
}


type PayType = 'balance' | 'weixin' | 'alipay';
export default class PurchasePage extends SpinerComponent<Props, State> {

    app: Application;
    shopping: ShoppingService;
    accout: AccountService;
    weixin: WeiXinService;

    constructor(props) {
        super(props);
        this.state = { payType: 'balance' };
        this.app = this.props.app;

        this.shopping = this.props.createService(ShoppingService);
        this.accout = this.props.createService(AccountService);
        this.weixin = this.props.createService(WeiXinService);
    }

    private balancePurchase(order: Order) {
        console.assert(order.Sum != null);
        console.assert(order.Sum == order.Amount + order.Freight);
        return this.accout.payOrder(order.Id, order.Sum);
    }


    private async weixinPurchase(order: Order) {
        console.assert(order.Sum != null);
        console.assert(order.Sum == order.Amount + order.Freight);

        let openid = this.weixin.openid();
        console.assert(openid != null);

        let args = await this.weixin.getPayArgs(openid, order);
        WeixinJSBridge.invoke('getBrandWCPayRequest', args, function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                window.location.href = '#Shopping/OrderList';
            }
        });
    }

    async loadData(): Promise<Partial<State>> {
        let order = await this.shopping.order(this.props.data.id);
        return { order };
    }

    pay() {
        let order = this.state.order;
        if (this.state.payType == "weixin") {
            return this.weixinPurchase(order);
        }
        return this.balancePurchase(order).then(() => {
            this.app.redirect('shopping/orderList');
        })
    }

    render() {
        let { order, payType } = this.state;
        return <>
            <header>
                {defaultNavBar(this.props.source, {
                    title: '订单概况',
                    // back: () => {
                    //     if (page.previous != null && page.previous.name == 'shopping.orderList') {
                    //         app.back();
                    //         return;
                    //     }
                    //     app.redirect('shopping_orderList');
                    // }
                })}
            </header>
            <section>
                <div className="container">
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>订单状态</label>
                        <div className="col-xs-9" style={{ color: '#f70' }}>
                            {this.shopping.orderStatusText(order.Status)}
                        </div>
                    </div>
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>订单编号</label>
                        <div className="col-xs-9">{order.Serial}</div>
                    </div>
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>订单总计</label>
                        <div className="col-xs-9 price">￥{order.Sum.toFixed(2)}</div>
                    </div>
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>收货信息</label>
                        <div className="col-xs-9">{order.ReceiptAddress}</div>
                    </div>
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>发票信息</label>
                        <div className="col-xs-9">{order.Invoice}</div>
                    </div>
                    <div className="row" style={{ paddingBottom: 10 }}>
                        <label className="col-xs-3" style={{ paddingRight: 0 }}>下单时间</label>
                        <div className="col-xs-9" data-bind="text:['{0:g}', order.OrderDate]">
                            {formatDate(order.OrderDate)}
                        </div>
                    </div>
                    {order.Remark ?
                        <div data-bind="visible:ko.unwrap(order.Remark)" className="row" style={{ paddingBottom: 10 }}>
                            <label className="col-xs-3" style={{ paddingRight: 0 }}>订单备注</label>
                            <div className="col-xs-9">
                                {order.Remark}
                            </div>
                        </div> : null}
                    <div style={{ marginBottom: 10 }}>
                        提示：请在下单24小时内付款，过期后订单将自动取消。
                        </div>
                    <hr className="row" />
                    <button className={payType == "balance" ? "cust-prop selected" : "cust-prop"}
                        onClick={e => this.setState({ payType: "balance" })}>
                        余额支付
                    </button>
                    <button className={payType == "weixin" ? "cust-prop selected" : "cust-prop"}
                        onClick={e => this.setState({ payType: "weixin" })}>
                        微信支付
                    </button>
                </div>
            </section>
            <footer>
                {order.Status == 'WaitingForPayment' ?
                    <div className="container">
                        <div className="form-group">
                            <button className="btn btn-block btn-primary"
                                ref={(o: HTMLButtonElement) => {
                                    if (!o) return;
                                    o.onclick = ui.buttonOnClick(() => this.pay())
                                }}>立即支付</button>
                        </div>
                    </div> : null}
            </footer>
        </>
    }
}

// shopping.order(page.data.values["id"]).then(order => {
//     ReactDOM.render(<PurchasePage order={order} />, page.element);
// })